<?php

/*
	Class: Pageparts_AdminController

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>

	About: See Also
		- <Cts_Controller_Action_Admin>
*/
class Pageparts_AdminController extends Cts_Controller_Action_Admin {

	/* Group: Instance Methods */

	/*
		Function: init
	*/
	function init() {
		parent::init();
	}

	/* Group: Actions */

	/*
		Function: index

		View Variables:
	*/
	function indexAction() {
		$request = new Cts_Request($this->getRequest());
		$pages_table = new PagepartsViewPages();
		$content_table = new PagepartsViewContent();
		$where = null;
		if ($request->has('q')) {
			$content_table->_keyword_search_field_names = array('metadata');
			$tmp_content = $content_table->fetchAll($content_table->select()
				->where('metadata like ?', '%'.$request->q.'%')
				->orWhere('part_name like ?', '%'.$request->q.'%')
				->orWhere('short_name like ?', '%'.$request->q.'%')
				->orWhere('page_url_rewrite like ?', '%'.$request->q.'%')
				->orWhere('page_template_name like ?', '%'.$request->q.'%')
				->orWhere('page_short_name like ?', '%'.$request->q.'%')
				->orWhere('page_title like ?', '%'.$request->q.'%')
				->orWhere('category_name like ?', '%'.$request->q.'%'));
			$page_ids = array();
			if (!is_null($tmp_content)) {
				$tmp_content = $tmp_content->toArray();
				foreach ($tmp_content as $content) {
					$page_ids[] = $content['page_id'];
				}
				$where = 'id in ('.implode(',', $page_ids).')';
			} else {
				$where = $pages_table->getWhereClauseForKeywords($request->q);
			}
			$this->view->q = $request->q;
		}
		// $params = array();
		// $per_page = Cts_Registry::get('admin_contentpages_per_page');
		// $page = $this->_request->getParam('page', 0);
		// $total = $pages_table->getCountByWhereClause($where);
		// $url = "/pageparts/admin/index";
		$order = "category_name asc";
		// $this->makePager($page, $per_page, $total, $url, $params);
		// $this->view->contentpages = $pages_table->fetchAllArray($where, $order, $per_page, $per_page * $page);
		$this->view->contentpages = $pages_table->fetchAllArray($where, $order);
	}

	/*
		Function: partlistAction
			Lists the parts of a page that can be edited.
	*/
	function listpartsAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('page_id')) {
        	$this->_redirect("/default/auth/missing");
		} else {
			$page_id = $request->page_id;
			$pages_table = new PagepartsViewPages();
			$parts_table = new PagepartsViewParts();
			$content_table = new PagepartsViewContent();
			$where = $parts_table->getAdapter()->quoteInto("page_id = ?", $page_id);
			$tmp_parts = $parts_table->fetchAllArray($where);
			$parts = array();
			foreach ($tmp_parts as $part) {
				$part['latest_version'] = $content_table->getLatestVersion($part['id'], $this->locale_code);
				$parts[] = $part;
			}
			$this->view->pageparts = $parts;
			$tmp_page = $pages_table->findArray($page_id);
			$this->view->page = $tmp_page;
			$this->view->page_id = $page_id;
			$this->view->page_title = "Site Content - ".$tmp_page['category_name']." - ".$tmp_page['title'];
		}
	}

	/*
		Function: listcontent
			Lists the versions of content of a particular page part.
	*/
	function listcontentAction() {
		$request = new Cts_Request($this->getRequest());
		if (!$request->has('part_id')) {
        	$this->_redirect("/default/auth/missing");
		} else {
			$parts_table = new PagepartsViewParts();
			$content_table = new PagepartsViewContent();
			$part_id = $request->part_id;
			$pagepart = $parts_table->findArray($part_id);
			$this->view->pagepart = $pagepart;

			if ($content_table->hasDraft($part_id, $this->locale_code)) {
				$drafts = $content_table->fetchAllArray(
					$content_table->select()
					->where("part_id = ?", $part_id)
					->where("locale = ?", $this->locale_code)
					->where("(active = 0 or publish_on is null or publish_on > '".date(DB_DATETIME_FORMAT)."')")
					->order("version desc")
				);
				$this->view->drafts = $drafts;
			}

			if ($content_table->hasArchives($part_id, $this->locale_code)) {
				$versions = $content_table->fetchAllArray(
					$content_table->select()
					->where("part_id = ?", $part_id)
					->where("locale = ?", $this->locale_code)
					->where("active = 1 and publish_on is not null and publish_on <= '".date(DB_DATETIME_FORMAT)."'")
					->order("version desc")
				);
				$this->view->versions = $versions;
			}

			$this->view->page_title = "Site Content - ".$pagepart['category_name']." - ".$pagepart['page_title']." - ".$pagepart['name'];
		}
	}

	/*
		Function: edit
	*/
	function editpageAction() {
		$request = new Cts_Request($this->getRequest());
	   	$errors = array();
		$page_id = 0;
		if (!$request->has('id')) {
        	$this->_redirect("/default/auth/missing");
		} else {
			$pages_table = new PagepartsPages();
			$page_id = $request->id;
			if ($page_id == -1) {
				$this->view->page_title = "Create New Page";
				$contentpage = array(
					'id' => "-1",
					'category_id' => "0",
					'title' => "New Page",
				);
			} else {
				$this->view->page_title = "Edit Page";
				$contentpage = $pages_table->fetchArray($page_id);
			}
			if (count($contentpage) >= 1) {
				$categories_table = new PagepartsCategories();
				$this->view->categories = $categories_table->getOptions("Choose a Category...");
				$this->view->contentpage = $contentpage;
				$this->view->page_id = $page_id;
				if ($this->getRequest()->isPost()) {
					$request->addValidator("title", "Please enter a title.");
					$request->addValidator("category_id", "Please choose a category.");
					if (!$request->isValid()) {
						$errors = array_merge($errors, $request->getValidationErrors());
					}
					if (count($errors) <= 0) {
						$contentpage['category_id'] = $request->category_id;
						$contentpage['module'] = $request->modulename;
						$contentpage['title'] = $request->title;
						$this->view->contentpage = $contentpage;
						$params = array();
						if ($page_id >= 1) {
							// UPDATE EXISTING
							$params['contentpage'] = $contentpage;
							$params = $this->_cts_plugin->doFilter("pageparts_admin_editpage_pre_update", $params); // FILTER HOOK
							$contentpage = $params['contentpage'];
							$where = $pages_table->getAdapter()->quoteInto("id = ?", $contentpage['id']);
							if ($pages_table->update($contentpage, $where) >= 1) {
								$this->view->success = "Page successfully updated.";
								$this->view->contentpage = null;
							} else {
								$errors[] = "Unable to update the page due to a database error.";
							}
						} else {
							// INSERT NEW
							$contentpage['id'] = null;
							$contentpage['created_on'] = date(DB_DATETIME_FORMAT);
							$params['contentpage'] = $contentpage;
							$params = $this->_cts_plugin->doFilter("pageparts_admin_editpage_pre_insert", $params); // FILTER HOOK
							$contentpage = $params['contentpage'];
							$page_id = $pages_table->insert($contentpage);
							if ($page_id >= 1) {
								$this->view->success = "Page successfully added.";
								$this->view->contentpage = null;
								$this->view->page_id = $page_id;
							} else {
								$errors[] = "Unable to add the page due to a database error.";
							}
						}
					}
				}
			} else {
				$errors[] = "Content page not found.";
			}
		}
		$this->view->errors = $errors;
	}

	/*
		Function: editcontent

		View Variables:
			content - TBD
			success - TBD
			errors - TBD
			metadata - TBD
			pagepart - TBD
			
	*/
	function editcontentAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		if (!$request->has('part_id') || !$request->has('version')) {
			$this->_redirect("/default/auth/missing");
		} else {
			$part_id = $request->part_id;
			$version = $request->version;
			$locale = $this->locale_code;
			$content['locale'] = $locale;
			$parts_table = new PagepartsViewParts();
			$content_table = new PagepartsContent();
			$content_view = new PagepartsViewContent();
			$content = $content_table->findArray($part_id, $locale, $version);
			if (is_null($content)) {
				$is_new = true;
				$latest_version = $content_view->getLatestVersion($part_id, $locale);
				$content = array(
					'part_id' => $part_id,
					'locale' => $locale,
					'active' => 0,
					'created_by_username' => $this->_identity->username,
					'created_on' => date(DB_DATETIME_FORMAT),
				);
				if (is_null($latest_version)) {
					$content['metadata'] = serialize(array('html_content' => $this->_T("Enter New Content Here")));
					$content['version'] = 1;
				} else {
					$content['metadata'] = $latest_version['metadata'];
					$content['version'] = $content_view->getNextVersionNumber($part_id, $locale);
				}
			} else {
				$is_new = false;
			}
			if ($content['active'] == 1) {
				if (strtotime($content['publish_on']) > time()) {
					$status = $this->_T("This page is set to be published at a future date.");
				} else {
					$status = $this->_T("This page has been published.");
				}
			} else {
				$status = $this->_T("This page has not been published.");
			}
			$this->view->status = $status;
			$pagepart = $parts_table->findArray($part_id);
			if (is_null($pagepart)) {
				$errors[] = $this->_T("Invalid page part ID specified.");
			}
			if (!count($errors)) {
				$this->view->page_title = "Site Content - ".$pagepart['category_name']." - ".$pagepart['page_title']." &raquo; ".$pagepart['name'];
				$metadata = unserialize($content['metadata']);
				$this->view->content = $content;
				$this->view->template_name = $pagepart['template_name'];
				$this->view->metadata = $metadata;
				$this->view->pagepart = $pagepart;
				$this->view->version = $content['version'];
				$this->view->formaction = "/pageparts/admin/editcontent/part_id/".$part_id."/version/".$version;
				if ($this->getRequest()->isPost()) {
					foreach ($_POST as $key => $val) {
						if (strpos($key, "metadata_") == 0) {
							$metadata[str_replace("metadata_", "", $key)] = stripslashes($val);
						}
					}
					$content['metadata'] = serialize($metadata);
					$content['active'] = $request->checkbox('active');
					if($request->has("pubdate_Hour")) {
						$pubdate = mktime(
							$request->pubdate_Hour,
							$request->pubdate_Minute,
							$request->pubdate_Second,
							$request->pubdate_Month,
							$request->pubdate_Day,
							$request->pubdate_Year
						);
						if($pubdate === false) {
							$errors[] = $this->_T("Chosen publish date is not valid.");
						} elseif ($pubdate < time()) {
							$pubdate = time();
						}
						$content['publish_on'] = date(DB_DATETIME_FORMAT, $pubdate);
					}
					$validators = unserialize($pagepart['validators']);
					if ($validators !== false) {
						foreach ($validators as $key => $val) {
							// validation messages are already translated in the database
							// so there is no need to translate the ($val) values here
							$request->addValidator($key, $val);
						}
					}
					if (!$request->isValid()) {
						$errors = array_merge($errors, $request->getValidationErrors());
					} else {
						$this->view->content = $content;
						$this->view->metadata = $metadata;
						$content['last_modified_by_username'] = $this->_identity->username;
						$content['last_modified_on'] = date(DB_DATETIME_FORMAT);
						if ($is_new) {
							// INSERT
							$content_id = $content_table->insert($content);
							if (array_key_exists('part_id', $content_id) && array_key_exists('locale', $content_id)) {
								$this->view->success = "Content successfully created.";
								$this->view->content = null;
							} else {
								$errors[] = "Unable to add the content due to a database error.";
							}
						} else {
							// UPDATE
							$where = $content_table->getAdapter()->quoteInto("part_id = ?", $content['part_id']);
							$where .= $content_table->getAdapter()->quoteInto(" and locale = ?", $content['locale']);
							$where .= $content_table->getAdapter()->quoteInto(" and version = ?", $content['version']);
							if ($content_table->update($content, $where) >= 1) {
								$this->view->success = "Content successfully updated.";
								$this->view->content = null;
							} else {
								$errors[] = "Unable to update the content due to a database error.";
							}
						}
					}
				}
			}
		}
		$this->view->errors = $errors;
	}

	/*
		Function: viewcontentAction
	*/
	function viewcontentAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		if (!$request->has('part_id') || !$request->has('version')) {
			$this->_redirect("/default/auth/missing");
		} else {
			$part_id = $request->part_id;
			$version = $request->version;
			$locale = $this->locale_code;
			$content['locale'] = $locale;
			$parts_table = new PagepartsViewParts();
			$content_table = new PagepartsContent();
			$content_view = new PagepartsViewContent();
			$content = $content_table->findArray($part_id, $locale, $version);
			$is_new = false;
			$pagepart = $parts_table->findArray($part_id);
			if (is_null($pagepart)) {
				$errors[] = $this->_T("Invalid page part ID specified.");
			}
			if (!count($errors)) {
				$this->view->page_title = "Site Content - ".$pagepart['category_name']." - ".$pagepart['page_title']." &raquo; ".$pagepart['name'];
				$metadata = unserialize($content['metadata']);
				$this->view->content = $content;
				$this->view->template_name = $pagepart['template_name'];
				$this->view->metadata = $metadata;
				$this->view->pagepart = $pagepart;
				$this->view->version = $content['version'];
			}
		}
		$this->view->errors = $errors;
	}

	/*
		Function: delete
	*/
	function deletepageAction() {
	}

	/*
		Function: deletepartAction
	*/
	function deletepartAction() {
	}

	/*
		Function: bulkdelete
	*/
	function bulkdeletepagesAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		if ($request->has('bulk_checkbox')) {
			$page_ids = $request->bulk_checkbox;
			$pages_table = new PagepartsPages();
			if ($this->getRequest()->isPost()) {
				if ($pages_table->deleteBulk($page_ids)) {
					$this->view->success = "Pages deleted.";
				} else {
					$errors[] = "Unable to delete the pages due to a database error.";
				}
			} else {
				$pages = $pages_table->getBulk($page_ids);
				if (count($pages) >= 1) {
					$this->view->contentpages = $pages;
				} else {
					$errors[] = "No pages found.";
				}
			}
		} else {
			$errors[] = "No pages were selected.";
		}
	}

	/*
		Function: inventory
			Gets a full inventory of all pageparts content in the system.
	*/
	function inventoryAction() {
		$request = new Cts_Request($this->getRequest());
		$content_table = new PagepartsViewContent();
		$tmp_versions = $content_table->fetchAllArray($content_table->select()
			->where("active = 1 and publish_on is not null and publish_on <= '".date(DB_DATETIME_FORMAT)."'")
			->order("version desc")
		);
		$versions = array();
		foreach ($tmp_versions as $version) {
			$version['metadata'] = unserialize($version['metadata']);
			$versions[] = $version;
		}
		$this->view->versions = $versions;
		header('Content-type: text');
	}

}
